package com.canbot.u05.activity.customvoice

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.View
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.*
import com.canbot.u05.activity.customvoice.adapter.CustomDialogPicAdapter
import com.canbot.u05.activity.customvoice.bean.CustomImageData
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.network.SalesApi
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.PathConst
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_custom_dialog_add_pic.*
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.ArrayList
import java.util.concurrent.TimeUnit

/**
 * CustomDialogAddPicActivity
 *
 * @author  Liu.Heng
 * @date  2019/5/29
 */
class CustomDialogAddPicActivity : BaseActivityNoTitle() {

    private lateinit var mCustomDialogPicAdapter: CustomDialogPicAdapter

    private lateinit var mCustomImageData: MutableList<CustomImageData>

    private lateinit var dialogLoading: Dialog

    /**超时时间100s*/
    private val timeOut = 100

    private var currentPosition = -1

    private lateinit var picPath: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_custom_dialog_add_pic)
        val intent = intent
        picPath = intent.getStringExtra("picPath")
        initView()
    }


    fun initView() {
        getData()

        mCustomDialogPicAdapter = CustomDialogPicAdapter(this, mCustomImageData, object : CustomDialogPicAdapter.Callback {
            override fun clickEvent(v: View, position: Int) {
                my_next.visibility = View.VISIBLE
                mCustomDialogPicAdapter.setChecked(position)
                currentPosition = position
                picPath = mCustomImageData[position].imagePath
            }
        })
        pic_recyclerView.layoutManager = GridLayoutManager(this@CustomDialogAddPicActivity, 4) //网格布局，每行为4
        pic_recyclerView.adapter = mCustomDialogPicAdapter

        my_back.setOnClickListener(::onClick)
        my_next.setOnClickListener(::onClick)
    }

    private fun getData() {
        mCustomImageData = ArrayList()
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this@CustomDialogAddPicActivity, resources.getString(R.string.request))
        dialogLoading.show()
        val url = "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/"
        val retrofit = Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .client(setTimeOut())
                .build()
        val salesApi = retrofit.create(SalesApi::class.java)
        val pic = salesApi.getPic("/uupic")
        pic.enqueue(object : Callback<JsonResponse> {
            override fun onResponse(call: Call<JsonResponse>, response: Response<JsonResponse>) {
                dialogLoading.dismiss()
                if (response.body() != null) {
                    val path = response.body()
                    Log.e("ChoosePicActivity", response.isSuccessful.toString() + " " + path)
                    if (path != null) {
                        if (path.rc == -1) {
                            return
                        }
                        val result = JSON.parseArray(path.result.toString(), String::class.java)
                        loge("result == $result")
                        result.withIndex().forEach {
                            val s = it.value
                            loge("编辑图片原图片设置选中picPath$picPath------$s")

                            if (picPath.isNotEmpty() && picPath == s) {
                                val map = CustomImageData(s)
                                mCustomImageData.add(map)
                                mCustomDialogPicAdapter.setChecked(it.index)
                            } else {
                                val map = CustomImageData(s)
                                mCustomImageData.add(map)
                            }
                        }
                    }
                    if (mCustomImageData.isEmpty()) {
                        my_next.visibility = View.GONE
                        no_pic_relativeLayout.visibility = View.VISIBLE
                        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_tpwk_001.wav")
                        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "30")
                    } else {
                        if (picPath.isNotEmpty()) {
                            my_next.visibility = View.VISIBLE
                        }else {
                            my_next.visibility = View.GONE
                        }
                        mCustomDialogPicAdapter.notifyDataSetChanged()
                    }
                }
            }

            override fun onFailure(call: Call<JsonResponse>, t: Throwable) {
                runOnUiThread {
                    my_next.visibility = View.GONE
                    dialogLoading.dismiss()
                    showToast(getString(R.string.network_error))
                }
            }
        })

    }

    /**
     * 设置超时
     *
     * @return
     */
    private fun setTimeOut(): OkHttpClient {
        return OkHttpClient.Builder()
                .connectTimeout(timeOut.toLong(), TimeUnit.SECONDS)
                .writeTimeout(timeOut.toLong(), TimeUnit.SECONDS)
                .readTimeout(timeOut.toLong(), TimeUnit.SECONDS)
                .build()

    }

    private fun onClick(view: View) {

        when (view.id) {
            R.id.my_back -> {
                setResultCanceled()
                finish()
                overridePendingTransitionExt()
            }
            R.id.my_next -> {
                val intent = Intent()
                intent.putExtra("picPath", picPath)
                setResultOK(intent)
                finish()
                overridePendingTransitionExt()
            }
            else -> {
            }
        }
    }
}
